"""
@name         获取线杆工单号
@version      1.0
@time         2025/04/07 16:52:49
@description  Retrieve data from the top hazard database and provide a complaint work order number.
@author       liuYanXiang,652455342@qq.com
@match        https://133.96.90.208/
@Must-do      Fix DingDing roboot token and @-mentioned mobile number.
              The authorization may expire. If the acquisition fails, please update the authorization.9_Authorization.
"""

import requests
import time
import json
from openpyxl import Workbook


def get_authorization():
    try:
        with open('9_Authorization', 'r') as file:
            for line in file:
                if line:
                    return line
    except FileNotFoundError:
        print("9_Authorization file not found.")
    return None

def read_top_task_ids(file_path):
    try:
        with open(file_path, 'r') as file:
            return [line.strip() for line in file.readlines()]
    except FileNotFoundError:
        print(f"错误：未找到文件 {file_path}")
        return []
    except Exception as e:
        print(f"错误：读取文件时发生未知错误 {e}")
        return []

def send_post_request(top_task_id):
    url = "https://133.96.90.208/prod-api/risk/autoComplaints/list"
    authorization = get_authorization()
    headers = {
        "Accept": "application/json, text/plain, */*",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Authorization": authorization,
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36"
    }
    payload = {
        "topTaskId": top_task_id,
        "onlineTransferredFlag": "",
        "telephoneNumber": "",
        "urgentFlag": "",
        "importanceFlag": "",
        "liability": "",
        "liabilitySpecialty": "",
        "riskCityName": "",
        "topRiskSource": "",
        "pageNum": 1,
        "pageSize": 500
    }

    try:
        response = requests.post(url, headers=headers, json=payload, verify=False, timeout=10)
        time.sleep(2)
        response.raise_for_status()
        return response.text
    except requests.RequestException as e:
        print(f"请求出错: {e}")
    except ValueError as e:
        print(f"解析响应内容出错: {e}")

if __name__ == "__main__":
    file_path = "9_top_task_id.txt"
    top_task_ids = read_top_task_ids(file_path)
    # 创建一个新的工作簿
    wb = Workbook()
    # 获取活动工作表
    ws = wb.active
    # 写入表头
    ws.append(["topTaskId", "orderId"])

    for top_task_id in top_task_ids:
        result = send_post_request(top_task_id)
        if result:
            data = json.loads(result)
            for row in data['rows']:
                topTaskId = row["topTaskId"]
                orderId = row["orderId"]
                # 将数据写入工作表
                ws.append([topTaskId, orderId])

    # 保存工作簿
    wb.save("output.xlsx")
    print("数据已成功写入 output.xlsx 文件。")